(function($) {
	$.getUrlParam = function(name) {
		var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
		var r = window.location.search.substr(1).match(reg);
		if (r != null) return unescape(r[2]);
		return null;
	}
})(jQuery);

const book = E = {
	numList: [],
	idList: [],
	editCost(fid, num) {
		$.ajax({
			url: url.path + 'cost/addCost',
			data: {
				did: $.getUrlParam("did"),
				uid: $('#uid').val(),
				fid: fid,
				num: num
			},
			type: 'post',
			dataType: 'json',
			success: function(res) {
				if (res.code == 200) {

				}
			},
			error: function() {
				//失败后显示
				alert('修改失败')
			}
		})

	},
	queryOne() {
		var id = $.getUrlParam("did");
		$.ajax({
			type: 'get',
			url: url.path + 'dingdan/queryOne',
			data: {
				id: id
			},
			dataType: 'json',
			success: function(res) {
				// var res = eval("(" + res + ")");
				let userstate = null;
				if (res.data.userState == 0) {
					userstate = "未查看"
				} else if (res.data.userState == 1) {
					userstate = "已通过"
				} else if (res.data.userState == 2) {
					userstate = "未通过"
				}
				if (res.code == "200") {
					$('#woNumber').text(res.data.dno);
					$('#contactNameDetail').text(res.data.lxrname);
					$('#contactPhoneDetail').text(res.data.lxrphone);
					$('#faultLocationDetail').text(res.data.address);
					$('#faultReasonDetail').text(res.data.description);
					$('#faultImage1').attr('src', res.data.img1);
					$('#faultImage2').attr('src', res.data.img2);
					$('#faultImage3').attr('src', res.data.img3);
					$('#repairDateDetail').text(E.timestampToDate(res.data.date));
					$('#faultLocationDetail').text(res.data.address);
					$('#wname').text(res.data.wname);
					$('#wphone').text(res.data.wphone);
					$('#wid').val(res.data.wid);
					$('#uid').val(res.data.uid);
					$('#userstate').text(userstate);
					$('#userssss').val(res.data.userState);
				} else {
					alert(res.msg);
					$('#captchaContainer').data('sliderCaptcha').reset();
					$('#captchaContainer').data('sliderCaptcha').init();
					$('#xyb').attr('disabled', true).css({
						'background-color': '#ccc',
						'cursor': 'not-allowed',
						'border-color': '#ccc'
					});
				}
			}
		});
	},
	timestampToDate(timestamp) {
		const date = new Date(timestamp); // 将时间戳转换为Date对象
		const options = {
			year: 'numeric',
			month: 'long',
			day: 'numeric'
		}; // 定义日期格式
		return new Intl.DateTimeFormat('zh-CN', options).format(date); // 使用Intl.DateTimeFormat进行格式化
	},
	edit(state) {
		var isAdd = confirm("是否确认执行当前操作?")
		if (isAdd) {
			var currentDate = new Date();
			var year = currentDate.getFullYear();
			var month = String(currentDate.getMonth() + 1).padStart(2, '0');
			var day = String(currentDate.getDate()).padStart(2, '0');

			var formattedDate = `${year}-${month}-${day}`;

			var userstate = 1;
			if (state == 5) {
				userstate = 0;
			}
			$.ajax({
				url: url.path + 'dingdan/edit',
				data: {
					id: $.getUrlParam("did"),
					state: state,
					wid: $('#wid').val(),
					wname: $('#wname').text(),
					wphone: $('#wphone').text(),
					enddate: "",
					senddate: formattedDate,
					userstate: userstate
				},
				type: 'post',
				dataType: 'json',
				success: function(res) {
					if (res.code == 200) {

						if (state == 5) {
							window.location.href = "yyxx.html?did=" + $.getUrlParam("did");
						} else if (state == 2) {
							window.location.href = "yyxxDZF.html?did=" + $.getUrlParam("did");
						} else if (state == 7) {
							window.location.href = "yyxxYQX.html?did=" + $.getUrlParam("did");
						} else if (state == 4) {
							window.location.href = "yyxxDSH.html?did=" + $.getUrlParam("did");
						}
					}
				},
				error: function() {
					alert('修改失败')
				}
			})
		}
	},
	delCost() {
		$.ajax({
			url: url.path + 'cost/delCost',
			data: {
				did: $.getUrlParam("did"),
				uid: $('#uid').val(),
			},
			type: 'post',
			dataType: 'json',
			success: function(res) {
				if (res.code == 200) {}
			},
			error: function() {
				//失败后显示
				alert('删除失败')
			}
		})
	},
	feiyong() {
		var _clist = $('#shoufei');
		var did = $.getUrlParam("did");
		var uid = $('#uid').val();
		var zongji = 0;
		zongji = parseInt(zongji);
		$.ajax({
			type: 'get',
			url: url.path + 'cost/getCostList',
			data: {
				uid: uid,
				did: did
			},
			dataType: 'json',
			success: function(res) {
				if (res.code == 200) {
					_clist.empty(); // 将容器清空
					let list = res.data;
					let listnum = 0;
					$(list).each(function(i, e) {
						let heji = e.fprice * e.num;
						let _tr = $(`<div class="charge-item">` + e.fname + `(` + e.fd + `)` + `
					<span class="float-end">x ` + e.num + `</span>
						<p class="text-muted small">￥` + e.fprice + `元/米</p>
					</div>`)
						zongji = zongji + parseInt(heji);
						_clist.append(_tr);
						listnum++;
					});
					let zong = $(`<div class="charge-summary">共` + listnum + `项,合计:￥<span id="heji">` +
						zongji +
						`</span></div>`);
					_clist.append(zong)
				}
			},
			error() {}
		});
	},
	feiyong1() {
		var _clist = $('#_tbody');
		$.ajax({
			url: url.path + 'caol/lise',
			type: 'get',
			data: {},
			dataType: 'json',

			success: function(res) {
				if (res.code == 200) {
					_clist.empty(); // 将容器清空
					let list = res.data;
					let he = $('#he');
					$(list).each(function(i, e) {
						let _num = $('#num').val();

						let _tr = $(`<tr data-price="` + e.price + `"></tr>`)
						let _tds = $(`
						            <td type="hide" id="fid">` + e.fid + `</td>
									<td>` + e.name + `</td>
						            <td>` + e.unit + `</td>
						            <td>` + e.price + `</td>
						    `)
						let _td = $(`<td></td>`)
						let num = $(
							`<input type="number" id="num" class="qty-input" value="0" min="0">`
						);
						let _tdd = $(`<td class="subtotal"></td>`)
						let all = $(
							`<p></p>`);
						_td.append(num);
						_tdd.append(all)
						_tr.append(_tds).append(_td).append(_tdd);
						_clist.append(_tr);

						num.on('change', function() {
							let value = parseInt($(this).val());
							if (value > 0) {
								E.numList.push(value);
								E.idList.push(e.fid);
								console.log('numList:', E.numList);
								console.log('idList:', E.idList);
							}
						});
					});

				}
			}
		});
	}
}
$(function() {

	E.queryOne();
	E.feiyong();

	$('#edit1').click(function() {
		$('#myModal').modal('show');
		E.feiyong1();
	});

	function calcSubtotal(row) {
		// 强化数值转换
		const price = parseFloat(row.data('price')) || 0; // 处理缺失属性
		const rawQty = row.find('.qty-input').val().trim(); // 获取原始值
		const qty = Math.max(0, parseInt(rawQty) || 0); // 处理非数字输入

		const subtotal = (price * qty).toFixed(2);
		row.find('.subtotal').text(subtotal);
	}

	// 计算全局统计
	function calcTotal() {
		let totalCount = 0;
		let totalAmount = 0;

		$('.fee-table tbody tr').each(function() {
			const qty = parseInt($(this).find('.qty-input').val()) || 0;
			const subtotal = parseFloat($(this).find('.subtotal').text()) || 0; // 处理文本转换

			if (!isNaN(subtotal) && qty > 0) { // 双重校验
				totalCount++;
				totalAmount += subtotal;
			}
		});

		$('#totalCount').text(totalCount);
		$('#totalAmount').text(totalAmount.toFixed(2));
	}

	// 输入事件监听
	$('.fee-table').on('input', '.qty-input', function() {
		const row = $(this).closest('tr');
		calcSubtotal(row);
		calcTotal();
	});

	// 初始化计算
	$('.fee-table tbody tr').each(function() {
		calcSubtotal($(this));
	});
	calcTotal();

	// 按钮事件
	$('#btn-close').click(() => $('#myModal').modal('hide'));
	$('#btn-submit').click(() => {
		alert(`提交成功！总金额：￥${$('#totalAmount').text()}`);
		E.delCost();
		for (var i = 0; i < E.idList.length; i++) {
			let nummm = E.numList[i];
			let fiddd = E.idList[i];
			E.editCost(fiddd, nummm);
		}
		E.edit(4);
		// 隐藏模态框
		$('#myModal').modal('hide');
		E.idList.length = 0;
		E.numList.length = 0;
	});
	$('#edit3').click(function() {
		E.edit(7);
	})
})